<script setup lang="ts">
import Pagination from "@/components/pagination/index.vue";
import { Search } from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import { fetchGoodsList } from '@/api/goods'
import { fetchPostGoodsApply } from '@/api/goods/apply'
import { filterDate } from '@/utils/format'
import type { FormInstance, FormRules } from "element-plus";
import { useUserStore } from "@/store/modules/user";

let showInfoDialog = ref(false); // 是否展示物资信息编辑框
// 表单数据
let tableData = reactive([])
// 实际传递的条件
const listQuery = reactive({
  currentPage: 1,
  name: undefined, // 名称
  type: 0, // 类型
  status: undefined, // 招新状态
  pageSize: 10,
  form: undefined, // 活动形式
  category: 0
})
// 显示在界面上的查询条件
const showQuery = reactive({
  currentPage: 1,
  name: undefined, // 名称
  type: 0, // 类型
  status: undefined, // 招新状态
  form: undefined, // 活动形式
})
const total = ref<number>(0)// 列表总数
// 查询
const handleSearch = () => {
  getPageList()
}
const tableLoading = ref(false)
// 获取列表
const getPageList = async () => {
  tableLoading.value = true
  listQuery.name = showQuery.name
  listQuery.status = showQuery.status
  listQuery.type = showQuery.type
  const res = await fetchGoodsList(listQuery)
  const { currentPage, data } = res.data
  listQuery.currentPage = showQuery.currentPage = currentPage
  total.value = res.data.total
  tableData = data
  tableLoading.value = false
}
onMounted(() => {
  getPageList()
})
/**
 * 重置表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
  // 重置验证规则
  if (!formEl) return;
  showInfoDialog.value = false
  formEl.resetFields();
};
let ruleForm = reactive({
  personId: useUserStore().userInfo.id,
  goodsId: undefined,
  applyType: undefined,
  applyNumber: undefined,
  applyReason: "",
  status: 0,
  stockNum: undefined,
  goodsName: ''
});
const typeOptions = [
  {
    value: 0,
    label: '领用物资'
  },
  {
    value: 1,
    label: '借用物资'
  }
]
const ruleFormRef = ref<FormInstance>();
const title = ref('')
const rules = reactive<FormRules>({
  applyNumber: [{ required: true, message: "请输入申请数量", trigger: "change" }],
  applyReason: [{ required: true, message: "请输入申请原因", trigger: "change" }],
});
// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (ruleForm.stockNum && ruleForm.applyNumber) {
        if (ruleForm.stockNum < ruleForm.applyNumber) {
          ElMessage({
            message: '申请数量需要小于库存数量',
            type: 'error'
          })
        } else {
          fetchPostGoodsApply(ruleForm).then((res: { code: number; }) => {
            if (res.code == 200) {
              ElMessage({
                message: '操作成功',
                type: 'success'
              })
            }
            showInfoDialog.value = false
            getPageList()
          })
        }
      }

    } else {
      console.log("error submit!", fields);
    }
  });
};

// 点击申请
const handleApply = (row: any) => {
  showInfoDialog.value = true
  ruleForm.applyType = row.type
  ruleForm.goodsName = row.name
  ruleForm.goodsId = row.id
  ruleForm.stockNum = row.stockNum
}
</script>

<template>
  <div class="goods-form-container">
    <div class="header flex justify-between items-center">
      <div class="flex items-center justify-between">
        <el-select v-model="showQuery.type" class="m-2" placeholder="物资类型" clearable>
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input v-model="showQuery.name" placeholder="根据名称查询" clearable />
        <el-button type="primary" :icon="Search" class="btn-green" @click="handleSearch()">查询</el-button>
      </div>
    </div>
    <el-table :data="tableData" stripe style="min-height: 40rem">
      <el-table-column type="index" label="序号" width="100" />
      <el-table-column prop="type" label="物资类型" show-overflow-tooltip>
        <template #default="scope">
          <div class="theme-blue">{{ scope.row.type == 0 ? '领用物资' : '借用物资' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" show-overflow-tooltip />
      <el-table-column prop="price" label="单价(元)" sortable />
      <el-table-column prop="createdAt" label="入库时间">
        <template #default="scope">
          <div>{{ filterDate(scope.row.createdAt) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="goodsInfo" label="物资信息" show-overflow-tooltip />
      <el-table-column prop="stockNum" label="当前库存" sortable>
        <template #default="scope">
          <div>{{ scope.row.stockNum + scope.row.unit }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <div class="theme-success" v-if="scope.row.stockNum > 10">
            {{ scope.row.type == 0 ? '可领用' : '可借用' }}
          </div>
          <div class="theme-warn" v-if="scope.row.stockNum <= 10 && scope.row.stockNum > 0">库存紧张
          </div>
          <div class="theme-error" v-if="scope.row.stockNum == 0">暂无库存</div>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="操作">
        <template #default="scope">
          <div class="theme-success">
            <el-button type="primary" link @click="handleApply(scope.row)">申请</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination :total="total" v-model:page="listQuery.currentPage" v-model:limit="listQuery.pageSize" hide-on-single-page
      @pagination="getPageList" />
    <!-- 编辑弹框 -->
    <div class="el-dialog-25">
      <el-dialog v-model="showInfoDialog" title="物资申请" @close="resetForm(ruleFormRef)">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
          <el-form-item label="物资类型：" class="el-form-item-full">
            <el-select v-model="ruleForm.applyType" disabled>
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="物资名称：">
            <el-input v-model="ruleForm.goodsName" disabled clearable />
          </el-form-item>
          <el-form-item label="库存数量：">
            <el-input v-model="ruleForm.stockNum" disabled clearable />
          </el-form-item>
          <el-form-item label="申请数量：" prop="applyNumber">
            <el-input v-model="ruleForm.applyNumber" placeholder="申请数量不能高于库存数量" clearable />
          </el-form-item>
          <el-form-item label="申请原因：" prop="applyReason">
            <el-input v-model="ruleForm.applyReason" maxlength="100" show-word-limit type="textarea" placeholder="请输入申请原因"
              clearable />
          </el-form-item>
          <el-form-item>
            <el-button @click="resetForm(ruleFormRef)" class="btn-white">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)" class="btn-green">
              确定
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss">
.goods-form-container {
  .header {

    .el-input,
    .el-select {
      margin-right: 20px;
      width: 20rem;
    }
  }
}
</style>
